import Data
import time
import sqlite3
import sys
from Function import Database

if sys.platform.startswith('win'):
    import pyperclip

database_address = "Database/Data.db"

def add_task_data(data):
    database_manager = sqlite3.connect(Data.database_address)
    cursor = database_manager.cursor()
    sql = 'insert into task(task_details, deadline) values (?, ?)'
    cursor.execute(sql, data)
    database_manager.commit()
    cursor.close()
    database_manager.close()


def delete_task_data_by_id(task_id):
    database_manager = sqlite3.connect(Data.database_address)
    cursor = database_manager.cursor()
    cursor.execute(f"delete from task where id = {task_id}")
    database_manager.commit()
    cursor.close()
    database_manager.close()


def add_task():
    task_details = input("请输入任务详情（输入0退出）（输入两个空格表示换行）：")
    if task_details != "0":
        print("\n\n"
              "特殊时间格式含义：\n"
              "0：没有截止时间；\n"
              "1：截止时间还未确定；\n"
              "2：尽快完成；"
              "\n\n")
        deadline = input('请输入截止时间(格式：month-day hour)：')
        # 如果输入的是时间格式，则保存为时间格式，否则保存为字符串
        if len(deadline) != 1:
            deadline = f"2025-{deadline}:00:00"
        elif deadline == "0":
            deadline = "no_dead_line"
        elif deadline == "1":
            deadline = "TBD"
        elif deadline == "2":
            deadline = "quickly"
        add_task_data((task_details, deadline))
        print("添加完成\n")
    else:
        print("没有任务添加\n")
    input("按Enter键继续……")


def task_display():
    full_content = ""
    no_time_task_list = []
    time_task_list = []
    not_expired_task_list = []
    # 需要尽快完成的任务列表
    quickly_task_list = []
    all_task_collection = []

    # 获取任务列表
    task_list = Database.read_data_to_list(database_address, "task")

    # 如果没有任务，则提示没有任务
    if not task_list:
        print("恭喜，所有任务均已完成！")
        print("")
    else:
        for task in task_list:
            try:
                time.strptime(task[2], "%Y-%m-%d %H:%M:%S")
                time_task_list.append(task)
            except ValueError:
                if task[2] == "quickly":
                    quickly_task_list.append(task)
                else:
                    no_time_task_list.append(task)

        # 有时间的任务列表以时间排序
        time_task_list.sort(key=lambda task_item: time.mktime(time.strptime(task_item[2], "%Y-%m-%d %H:%M:%S")),
                            reverse=False)

        # 将有截止时间的任务按照剩余时间分类
        for task in time_task_list:
            deadline_stamp = time.mktime(time.strptime(task[2], "%Y-%m-%d %H:%M:%S"))
            now_time_stamp = time.time()

            if deadline_stamp > now_time_stamp:
                # 如果任务未过期
                not_expired_task_list.append(task)
            elif now_time_stamp - deadline_stamp > 604800:
                # 任务已经过期7天，则根据任务id删除任务
                delete_task_data_by_id(task[0])

        # 将各个collection合在一起
        all_task_collection = all_task_collection + quickly_task_list
        all_task_collection = all_task_collection + not_expired_task_list
        all_task_collection = all_task_collection + no_time_task_list

        num_sort_emoji = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔢"]
        week_num_list = ["7", "1", "2", "3", "4", "5", "6"]
        print("任务汇总")
        full_content = full_content + "任务汇总" + "\n"

        if all_task_collection:
            # 遍历任务并显示
            for task_index, task in enumerate(all_task_collection):
                # 显示编号
                print(num_sort_emoji[task_index], end='')
                full_content = full_content + num_sort_emoji[task_index]

                # 将换行标识符“  ”换为换行“\n”
                task_content = task[1].replace('  ', '\n     ')
                # 如果任务中有链接，则使用👉
                if "http" in task_content:
                    task_content = task_content.replace("     http", "👉链接：http")
                # 显示任务
                print(task_content)
                full_content = full_content + task_content + "\n"
                # 处理时间显示
                if task[2] == "no_dead_line":
                    print(f'⏰无截止时间')
                    full_content = full_content + '⏰无截止时间'
                elif task[2] == "TBD":
                    print(f'⏰时间未确定')
                    full_content = full_content + '⏰时间未确定'
                elif task[2] == "quickly":
                    print(f'⏰尽快完成')
                    full_content = full_content + '⏰尽快完成'
                elif task[2]:
                    try:
                        print(f'⏰{time.strftime("%m月%d日%H时", time.strptime(task[2], "%Y-%m-%d %H:%M:%S"))}', end=" ")
                        full_content = full_content + f'⏰{time.strftime("%m月%d日%H时", time.strptime(task[2], "%Y-%m-%d %H:%M:%S"))} '
                        print(f"周{week_num_list[int(time.strftime('%w', time.strptime(task[2], '%Y-%m-%d %H:%M:%S')))]}")
                        full_content = full_content + f"周{week_num_list[int(time.strftime('%w', time.strptime(task[2], '%Y-%m-%d %H:%M:%S')))]}" + "\n"
                    except ValueError:
                        # 时间格式错误
                        print(f'⏰时间格式错误，值为：{task[2]}')
                        full_content = full_content + f'⏰时间格式错误，值为：{task[2]}'
                print("")
                full_content = full_content + "\n"

    if sys.platform.startswith('win'):
        # 将内容复制到剪切板
        pyperclip.copy(full_content)
    elif sys.platform.startswith('linux'):
        # 任务文本内容写入文件，方便后续复制到剪切板
        with open(".content.txt", "w", encoding="utf-8") as file:
            file.write(full_content)
